package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewSoftwareAdapter;
import net.oschina.app.adapter.ListViewSoftwareCatalogAdapter;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.SoftwareCatalogList;
import net.oschina.app.bean.SoftwareCatalogList.SoftwareType;
import net.oschina.app.bean.SoftwareList;
import net.oschina.app.bean.SoftwareList.Software;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BaseSoftwareListFragment extends MainPullToRefreshListFragment {
	public final static int HEAD_TAG_CATALOG = 0x001;
	public final static int HEAD_TAG_RECOMMEND = 0x002;
	public final static int HEAD_TAG_LASTEST = 0x003;
	public final static int HEAD_TAG_HOT = 0x004;
	public final static int HEAD_TAG_CHINA = 0x005;
    public final static int SCREEN_CATALOG = 0;
    public final static int SCREEN_TAG = 1;
    public final static int SCREEN_SOFTWARE = 2;
    
	protected ListViewSoftwareAdapter lvSoftwareAdapter;
	protected List<Software> lvSoftwareData = new ArrayList<Software>();
    protected Handler mSoftwareHandler;
    protected int lvSumData;
    protected int curHeadTag;
    protected int curLvSoftwareDataState;

	protected int curScreen = SCREEN_CATALOG;// 默认当前屏幕
	protected int curFirstSearchTag;
	protected int curSecondSearchTag;// 当前二级分类的Tag
	protected String curTitleLV1;// 当前一级分类标题 private ListView mlvSoftwareCatalog;

	protected ListView mlvSoftwareCatalog;
	protected ListViewSoftwareCatalogAdapter lvSoftwareCatalogAdapter;
	protected List<SoftwareType> lvSoftwareCatalogData = new ArrayList<SoftwareType>();
	protected Handler mSoftwareCatalogHandler;

	protected ListView mlvSoftwareTag;
	protected ListViewSoftwareCatalogAdapter lvSoftwareTagAdapter;
	protected List<SoftwareType> lvSoftwareTagData = new ArrayList<SoftwareType>();
	protected Handler mSoftwareTagHandler;
	protected PullToRefreshLayout refreshLayout1;
	protected PullToRefreshLayout refreshLayout2;
	protected PullToRefreshLayout refreshLayout3;
	public BaseSoftwareListFragment(int curHeadTag,
			OnBaseListFragmentResumeListener baseListFragmentResumeListener) {
		super(baseListFragmentResumeListener);
		this.curHeadTag = curHeadTag;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initSoftwareListView();
	}
	
    //初始化软件listview
	protected void initSoftwareListView()
    {
    	lvSoftwareAdapter = new ListViewSoftwareAdapter(getActivity(), lvSoftwareData, R.layout.software_listitem); 
    	listView.addFooterView(list_footer);//添加底部视图  必须在setAdapter前
    	listView.setAdapter(lvSoftwareAdapter); 
    	listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击头部、底部栏无效
        		if(view == list_footer) return;
        		        		
    			TextView name = (TextView)view.findViewById(R.id.software_listitem_name);
    			Software sw = (Software)name.getTag();

        		if(sw == null) return;
        		
        		//跳转
        		UIHelper.showUrlRedirect(view.getContext(), sw.url);
        	}
		});
    	listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
				//数据为空--不用继续下面代码了
				if(lvSoftwareData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(list_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				if(scrollEnd && curLvSoftwareDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					listView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					list_foot_more.setText(R.string.load_ing);
					list_foot_progress.setVisibility(View.VISIBLE);
					//当前pageIndex
					int pageIndex = lvSumData/AppContext.PAGE_SIZE;
					if(curHeadTag == HEAD_TAG_CATALOG)
						loadLvSoftwareTagData(curSecondSearchTag, pageIndex, mSoftwareHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
					else
					loadLvSoftwareData(curHeadTag, pageIndex, mSoftwareHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
			}
		});
    	
      	mSoftwareHandler = this.getLvHandler(listView, lvSoftwareAdapter,
				list_foot_more, list_foot_progress, AppContext.PAGE_SIZE);
    }
	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
    protected Notice handleLvData(int what, Object obj, int objtype,
			int actiontype) {
		SoftwareList list = (SoftwareList)obj;
		Notice notice = list.getNotice();
		//处理listview数据
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_INIT:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
			lvSumData = what;
			lvSoftwareData.clear();//先清除原有数据
			lvSoftwareData.addAll(list.getSoftwarelist());
			break;
		case UIHelper.LISTVIEW_ACTION_SCROLL:
			lvSumData += what;
			if(lvSoftwareData.size() > 0){
				for(Software sw1 : list.getSoftwarelist()){
					boolean b = false;
					for(Software sw2 : lvSoftwareData){
						if(sw1.name.equals(sw2.name)){
							b = true;
							break;
						}
					}
					if(!b) lvSoftwareData.add(sw1);
				}
			}else{
				lvSoftwareData.addAll(list.getSoftwarelist());
			}
			break;
		}	
		return notice;
	}
	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	protected Handler getLvHandler(final ListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler()
		{
			public void handleMessage(Message msg) {
				if(msg.what >= 0){						
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,
							msg.arg1);
					
					if(msg.what < pageSize){
						curLvSoftwareDataState = UIHelper.LISTVIEW_DATA_FULL;
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					}else if(msg.what == pageSize){					
						curLvSoftwareDataState = UIHelper.LISTVIEW_DATA_MORE;
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);
					}
					//发送通知广播
					if(notice != null){
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					curLvSoftwareDataState = UIHelper.LISTVIEW_DATA_MORE;
					more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(lv.getContext());
				}
				if(lvSoftwareData.size()==0){
					curLvSoftwareDataState = UIHelper.LISTVIEW_DATA_EMPTY;
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(View.GONE);
				mPullToRefreshAttacher.setRefreshComplete();
				if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
					lv.setSelection(0);
				}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
					lv.setSelection(0);
				}
			}
		};
	}
  	/**
     * 线程加载软件列表数据
     * @param searchTag 软件分类 推荐:recommend 最新:time 热门:view 国产:list_cn
     * @param pageIndex 当前页数
     * @param handler 处理器
     * @param action 动作标识
     */
	protected void loadLvSoftwareData(final int tag,final int pageIndex,final Handler handler,final int action){  
		
		String _searchTag = "";
		
		switch (tag) {
		case HEAD_TAG_RECOMMEND: 
			_searchTag = SoftwareList.TAG_RECOMMEND;
			break;
		case HEAD_TAG_LASTEST: 
			_searchTag = SoftwareList.TAG_LASTEST;
			break;
		case HEAD_TAG_HOT: 
			_searchTag = SoftwareList.TAG_HOT;
			break;
		case HEAD_TAG_CHINA: 
			_searchTag = SoftwareList.TAG_CHINA;
			break;
		}
		
		if(StringUtils.isEmpty(_searchTag)) return;		
		
		final String searchTag = _searchTag;
		
		mPullToRefreshAttacher.setRefreshing(true);
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				try {
					SoftwareList softwareList = appContext.getSoftwareList(searchTag, pageIndex, isRefresh);
					msg.what = softwareList.getPageSize();
					msg.obj = softwareList;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
				if(curHeadTag == tag)
					handler.sendMessage(msg);
			}
		}.start();
	} 
	// 初始化分类listview
	protected void initSoftwareCatalogListView() {
		lvSoftwareCatalogAdapter = new ListViewSoftwareCatalogAdapter(
				getActivity(), lvSoftwareCatalogData,
				R.layout.softwarecatalog_listitem);
		mlvSoftwareCatalog.setAdapter(lvSoftwareCatalogAdapter);
		mlvSoftwareCatalog
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						TextView name = (TextView) view
								.findViewById(R.id.softwarecatalog_listitem_name);
						SoftwareType type = (SoftwareType) name.getTag();

						if (type == null)
							return;

						if (type.tag > 0) {
							curTitleLV1 = type.name;
							curFirstSearchTag = type.tag;
							// 加载二级分类
							scrollToScreen(SCREEN_TAG);
							loadLvSoftwareCatalogData(type.tag,
									mSoftwareTagHandler,
									UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
						}
					}
				});

		mSoftwareCatalogHandler = getSoftwareCatalogLvHandler(mlvSoftwareCatalog);
	}

	protected Handler getSoftwareCatalogLvHandler(final ListView lv) {
		return new Handler() {
			public void handleMessage(Message msg) {

				mPullToRefreshAttacher.setRefreshComplete();

				if (msg.what >= 0) {
					SoftwareCatalogList list = (SoftwareCatalogList) msg.obj;
					Notice notice = list.getNotice();
					// 处理listview数据
					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSoftwareCatalogData.clear();// 先清除原有数据
						lvSoftwareCatalogData
								.addAll(list.getSoftwareTypelist());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						break;
					}

					lvSoftwareCatalogAdapter.notifyDataSetChanged();

					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					((AppException) msg.obj).makeToast(lv.getContext());
				}
			}
		};
	}

	// 初始化二级分类listview
	protected void initSoftwareTagListView() {
		lvSoftwareTagAdapter = new ListViewSoftwareCatalogAdapter(
				getActivity(), lvSoftwareTagData,
				R.layout.softwarecatalog_listitem);
		mlvSoftwareTag.setAdapter(lvSoftwareTagAdapter);
		mlvSoftwareTag
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						TextView name = (TextView) view
								.findViewById(R.id.softwarecatalog_listitem_name);
						SoftwareType type = (SoftwareType) name.getTag();

						if (type == null)
							return;

						if (type.tag > 0) {
							// 加载软件列表
							scrollToScreen(SCREEN_SOFTWARE);
							curSecondSearchTag = type.tag;
							loadLvSoftwareTagData(curSecondSearchTag, 0,
									mSoftwareHandler,
									UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
						}
					}
				});

		mSoftwareTagHandler = getSoftwareTagLvHandler(mlvSoftwareTag);
	}

	protected Handler getSoftwareTagLvHandler(final ListView lv) {
		return new Handler() {
			public void handleMessage(Message msg) {

				mPullToRefreshAttacher.setRefreshComplete();

				if (msg.what >= 0) {
					SoftwareCatalogList list = (SoftwareCatalogList) msg.obj;
					Notice notice = list.getNotice();
					// 处理listview数据
					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSoftwareTagData.clear();// 先清除原有数据
						lvSoftwareTagData.addAll(list.getSoftwareTypelist());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						break;
					}

					lvSoftwareTagAdapter.notifyDataSetChanged();

					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					((AppException) msg.obj).makeToast(lv.getContext());
				}
			}
		};
	}

	/**
	 * 线程加载软件分类列表数据
	 * 
	 * @param tag
	 *            第一级:0 第二级:tag
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	protected void loadLvSoftwareCatalogData(final int tag,
			final Handler handler, final int action) {
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					SoftwareCatalogList softwareCatalogList = appContext
							.getSoftwareCatalogList(tag);
					msg.what = softwareCatalogList.getSoftwareTypelist().size();
					msg.obj = softwareCatalogList;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;// 告知handler当前action
				handler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * 线程加载软件分类二级列表数据
	 * 
	 * @param tag
	 *            第一级:0 第二级:tag
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	protected void loadLvSoftwareTagData(final int searchTag,
			final int pageIndex, final Handler handler, final int action) {
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH
						|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				try {
					SoftwareList softwareList = appContext.getSoftwareTagList(
							searchTag, pageIndex, isRefresh);
					msg.what = softwareList.getSoftwarelist().size();
					msg.obj = softwareList;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;// 告知handler当前action
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	/**
	 * 返回事件
	 */
	protected void back() {
		getFragmentActivity().toggle();
	}

	protected void scrollToScreen(int curScreen) {
		this.curScreen = curScreen;
		switch (curScreen) {
		case SCREEN_CATALOG:
			refreshLayout1.setVisibility(View.VISIBLE);
			refreshLayout2.setVisibility(View.GONE);
			refreshLayout3.setVisibility(View.GONE);
			break;
		case SCREEN_TAG:
			refreshLayout1.setVisibility(View.GONE);
			refreshLayout2.setVisibility(View.VISIBLE);
			refreshLayout3.setVisibility(View.GONE);
			break;
		case SCREEN_SOFTWARE:
			refreshLayout1.setVisibility(View.GONE);
			refreshLayout2.setVisibility(View.GONE);
			refreshLayout3.setVisibility(View.VISIBLE);
			break;

		}
	}

	@Override
	public void onRefreshStarted(View view) {
		loadLvSoftwareData(curHeadTag, 0, mSoftwareHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
	}

	@Override
	public void showList() {
		if (!isHasInit()) {
			loadLvSoftwareData(curHeadTag, 0, mSoftwareHandler, UIHelper.LISTVIEW_ACTION_INIT);
			setHasInit(true);
		}
	}

}
